package com.beisita.web.controller.common;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


public abstract class BaseActionAbstract implements BaseActionInterface {
    protected Map<String, Object> session;

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    }

    public HttpServletResponse getResponse() {
        return ((BaseActionAbstract) RequestContextHolder.getRequestAttributes()).getResponse();

    }

    public HttpSession getSession() {
        return getRequest().getSession();

    }

    public ServletContext getServletContext() {
        return ((BaseActionAbstract) RequestContextHolder.getRequestAttributes()).getServletContext();

    }

    public String getRequestUrl() {
        String url = getRequest().getRequestURI();
        String path = getRequest().getContextPath();
        if (path != null && !"".equals(path))
            return url.substring(path.length());
        return null;

    }

    public void responseToClient(String content) throws Exception {
        responseToClient(content, "text/plain");

    }

    public void responseToClient(String content, String contentType) throws Exception {
        getResponse().setCharacterEncoding("UTF-8");
        getResponse().setContentType(contentType);
        getResponse().getWriter().write(content);
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown"
                .equalsIgnoreCase(ip))
            ip = request.getHeader("Proxy-Client-IP");

        if (StringUtils.isEmpty(ip) || "unknown"
                .equalsIgnoreCase(ip))
            ip = request.getHeader("WL-Proxy-Client-IP");

        if (StringUtils.isEmpty(ip) || "unknown"
                .equalsIgnoreCase(ip))
            ip = request.getRemoteAddr();
        return ip;

    }

    public void setResponseNoCache() {
        getResponse().setHeader("progma", "no-cache");
        getResponse().setHeader("Cache-Control", "no-cache");
        getResponse().setHeader("Cache-Control", "no-store");
        getResponse().setDateHeader("Expires", 0L);

    }

    public void addCookie(String name, String value, int maxAge, String path, String domain) {
        if (!StringUtils.isEmpty(value))
            try {
                value = URLEncoder.encode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        Cookie cookie = new Cookie(name, value);

        cookie.setPath(path);
        if (maxAge > 0)
            cookie.setMaxAge(maxAge);
        getResponse().addCookie(cookie);

    }

    public String getCookieValueByName(String name) {
        Map<String, Cookie> cookieMap = readCookieMap();
        if (cookieMap.containsKey(name)) {
            Cookie cookie = cookieMap.get(name);
            String value = null;
            try {
                value = URLDecoder.decode(cookie.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return value;

        }
        return null;

    }

    public Cookie getCookieByName(String name) {
        Map<String, Cookie> cookieMap = readCookieMap();
        if (cookieMap.containsKey(name)) {
            Cookie cookie = cookieMap.get(name);
            return cookie;
        }
        return null;
    }

    protected Map<String, Cookie> readCookieMap() {
        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = getRequest().getCookies();
        if (null != cookies)
            for (int i = 0; i < cookies.length; i++)
                cookieMap.put(cookies[i].getName(), cookies[i]);
        return cookieMap;
    }


    public void cleanCookie(String cookieName, String path, String domain) {
        addCookie(cookieName, null, 0, path, domain);
    }

    public Cookie getCookiebyName(String cookieName) {
        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = getRequest().getCookies();
        if (null != cookies)
            for (int i = 0; i < cookies.length; i++)
                cookieMap.put(cookies[i].getName(), cookies[i]);
        if (cookieMap.containsKey(cookieName))
            return cookieMap.get(cookieName);
        return null;

    }


    public void sendPrintWithPdf(String fileName, byte[] bytes) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            getResponse().setContentType("application/pdf");
            getResponse().setCharacterEncoding("UTF-8");
            getResponse().setHeader("Content-Disposition", "inline;filename=" + fileName + ".pdf");
            getResponse().getOutputStream().write(bytes, 0, bytes.length);
            getResponse().getOutputStream().flush();
            getResponse().getOutputStream().close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    public void setSession(Map<String, Object> sess) {
        this.session = sess;

    }

}

